package com.wyx.httpService.jinyeService.impl;

import com.google.gson.Gson;
import com.wyx.pojo.constant.Info;
import com.wyx.pojo.constant.JinyeConstant;
import com.wyx.pojo.cookie.JinyeCookie;
import com.wyx.pojo.httpSmokeBean.jinyebean.Bean1;
import com.wyx.service.impl.SmokeServiceImpl;
import com.wyx.utils.commonUtil.CUtil;
import com.wyx.utils.jinyeUtil.JEncipherUtil;
import okhttp3.*;
import org.apache.tomcat.util.codec.binary.Base64;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.springframework.stereotype.Service;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.imageio.ImageIO;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

//在这儿有很多问题，需要高人指点
@Service
public class LoginServiceImpl {
    //    cookie 的 session 参数。作用是比对验证码
    public String session;


    //    中间参数
    public String _t;
    public String Tgc;
    public String execution;

    public String csrfToken;
    public String csrfToken_t;
    //    加密的密码
    public String encipherPassword;
    public String token;
    public String captcha;

    /**
     * 先获得  验证码，根据获取的验证码得到一个  SESSION
     * 之后获取_t这个参数
     */
    public void login() throws InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException {
        getCaptcha();
        getParam();
        validUser();
        getTgc();
        getYYTJSESSIONIDAndUiInfo();
    }

    /**
     * 得到验证码
     *
     * @return 返回验证码的byte数组
     */
    public void getCaptcha() {
        long modifiedTimestamp = System.currentTimeMillis() / 1000 * 1000; // 将后三位替换为0
        OkHttpClient client = new OkHttpClient();
        String url = "https://www.jinye.cn/cas/captcha.jpg" + "?id=" + modifiedTimestamp; // 替换为目标网址
        Cookie cookie = new Cookie.Builder()
                .name("SESSION")
                .value("234")
                .domain("www.jinye.cn")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .header("Cookie", cookie.toString())
                .build();
        byte[] captchaBytes = new byte[0];
        try {
            Response response = client.newCall(request).execute();
            captchaBytes = response.body().bytes();

            if (response.isSuccessful()) {
                Headers headers = response.headers();
                List<String> values = headers.values("Set-Cookie");
                for (String value : values) {
                    String[] cookieKeyValues = value.split(";");
                    String cookieKeyValue = cookieKeyValues[0].trim();
                    int index = cookieKeyValue.indexOf("=");
                    String cookieValue = cookieKeyValue.substring(index + 1);
                    session = cookieValue;
                }
            } else {
                System.out.println("请求失败了");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(captchaBytes);
            File file = new File("E:\\temp\\test\\t.jpg");
            if (!file.exists()) {
                boolean mkdirs = file.mkdirs();
                System.out.println(mkdirs);
            }
            ImageIO.write(ImageIO.read(bis), "jpg", file);
            bis.close();
            System.out.println("验证码图片保存成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取 _t  execution csrfToken_t参数
     */
    public void getParam() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://www.jinye.cn/cas/login?service=https://www.jinye.cn/marketing-orderplatform/ui/pages/index.html")
                .build();


        try {
            // 发送请求并获取响应
            Response response = client.newCall(request).execute();
            if (response.isSuccessful() && response.body() != null) {
                String string = response.body().string();
                Document document = Jsoup.parse(string);
                Element form = document.selectFirst("#fm1");
                String tValue = form.attr("action").split("_t=")[1];
                _t = tValue;
                Element executionEle = document.select("input[name=execution]").first();
                execution = executionEle.attr("value");
                Element csrfTokenEle = document.select("input[name=csrfToken_t]").first();
                String value = csrfTokenEle.attr("value");
                csrfToken_t = value;
            } else {
                System.out.println("Request failed");
            }
            String date1 = response.header("Date");
//            Sun, 31 Mar 2024 02:20:01 GMT
//            ukFanzGeh2%3DWvw9raY6qwHeTpZWKNa2vAIj6Pgjr258%3D
//正确的       F6XtH2LGA2%2Bp0wKwNGtmGHeTpZWKNa2vAIj6Pgjr258%3D
//错误的       SgkAR9IiAVK9OG2scOaAOXeTpZWKNa2vAIj6Pgjr258%3D

            String[] s = date1.split(" ");
            String s1 = s[3] + "-" + "3-31 " + s[4];
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            Date date = sdf.parse(s1);
            // 将时间转换为北京时间（GMT+8）
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            String beijingTime = sdf.format(date);
            System.out.println("北京时间：" + beijingTime);
            long time = date.getTime();
            long l = System.currentTimeMillis();
            System.out.println("时间戳：" + date.getTime());
            JinyeConstant.setTime(time + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取cookie TGC
     * https://www.jinye.cn/cas/login?_t=1716258900891
     */
    public void getTgc() {
        OkHttpClient client = new OkHttpClient();

        RequestBody requestBody = new FormBody.Builder()
                .add("username", "140105122422")
                .add("yytpasspword", "")
                .add("password", JEncipherUtil.urlEncode(encipherPassword))
                .add("execution", JEncipherUtil.urlEncode(execution))
                .add("loginBeforeEnableSetPkcorp", "true")
                .add("_eventId", "submit")
                .add("geolocation", "")
                .add("md5pwd", JEncipherUtil.urlEncode(encipherPassword))
                .add("csrfToken_t", JEncipherUtil.urlEncode(csrfToken_t))
                .add("isNeedVerifyCode", "true")
                .add("captcha", captcha)
                .add("token", token)
                .add("defaultPkCorp", "0")
                .add("pk_corp", "0001")
                .add("cipherText", "")
                .add("plainText", "")
                .add("csrfToken", JEncipherUtil.urlEncode(csrfToken_t))
                .add("submit", JEncipherUtil.urlEncode("登录中..."))
                .build();
        String str = "username=140105122422&yytpasspword=&password=T4X3L3qN1T%2BN0v8UjDKvUw%3D%3D&execution=b0d7c3b3-d408-4e16-b358-e7bd80830b54_ZXlKaGJHY2lPaUpJVXpVeE1pSjkuRnhwcURDT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XREZpWUNVNkVmT01OaEhEdDQ1eWlZbFRJak1TVmI1ejcvSUJVKytyQVEvWWhuc3VUVHpmS2Y3bzY5bzFWMkRRPS5ZVTZVZ29JTURnNW1wWm1iU29wOVRFbllxUWJSSXlTZ0c3VzhRTUdwRVdRc3JpbXRTeWFsZWhSLUh5TWhTTlNxVVhEYWtzQnAyN3ZrU1NDUHpMWFJkUQ%3D%3D&loginBeforeEnableSetPkcorp=true&_eventId=submit&geolocation=&md5pwd=T4X3L3qN1T%2BN0v8UjDKvUw%3D%3D&csrfToken_t=F6XtH2LGA2%2Bp0wKwNGtmGHeTpZWKNa2vAIj6Pgjr258%3D&isNeedVerifyCode=true&captcha=W1H3&token=d992adf0d13b403493dd739791dfd473&defaultPkCorp=0&pk_corp=0001&cipherText=&plainText=&csrfToken=F6XtH2LGA2%2Bp0wKwNGtmGHeTpZWKNa2vAIj6Pgjr258%3D&submit=%E7%99%BB%E5%BD%95%E4%B8%AD...";
        FormBody formBody = (FormBody) requestBody;
        String[] split = str.split("&");
        for (int i = 0; i < formBody.size(); i++) {
            System.out.println("正确的" + split[i]);
            System.out.println("错误的" + formBody.name(i) + "=" + formBody.value(i));
            System.out.println("--");
        }
        Request request = new Request.Builder()
                .url("https://www.jinye.cn/cas/login?_t=" + _t)
                .post(formBody)
                .header("Cookie", "SESSION=" + session)
                .build();

        try {
            // 发送请求并获取响应
            Response response = client.newCall(request).execute();
            if (response.isSuccessful() && response.body() != null) {
//                TODO: 在这儿 返回值为空
                System.out.println(response.headers().toString());
                String set_cookie = response.header("Set-Cookie");
                System.out.println(set_cookie);
            } else {
                System.out.println("Request failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 校验用户  密码和验证码
     * 97077774-42c3-4c9f-ac99-ac575ab58bd5
     * cac35a0c-9a99-4a28-ab1d-b960fe884b72
     */
    public void validUser() throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
        OkHttpClient client = new OkHttpClient();
        System.out.println("请输入验证码：");
        String verifyCode = new Scanner(System.in).nextLine();
        captcha = verifyCode;
        // 将加密后的数据转换为Base64字符串
        byte[] bytes = JEncipherUtil.aesEncipher("@Wy123456");
        String encipherPasswordss = Base64.encodeBase64String(bytes);
        encipherPassword = encipherPasswordss;
        RequestBody requestBody = new FormBody.Builder()
                .add("username", "140105122422")
                .add("password", encipherPasswordss)
                .add("verifycode", verifyCode)
                .add("csrfToken", csrfToken_t)
                .build();
        Request request = new Request.Builder()
                .url("https://www.jinye.cn/cas/validUser")
                .header("Cookie", "SESSION=" + session)
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                .header("Referer", "https://www.jinye.cn/cas/login?service=https%3A%2F%2Fwww.jinye.cn%2Fmarketing-orderplatform%2Fcascallback")
                .header("Sec-Ch-Ua-Platform", "\"Windows\"")
                .header("Origin", "https://www.jinye.cn")
                .header("User-Agent",
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String responseData = response.body().string();
                String s = CUtil.JsonFormatting(responseData);
                System.out.println(s);
                token = new Gson().fromJson(s, Bean1.class).getToken();
                System.out.println("得到的token 是：" + token);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getYYTJSESSIONIDAndUiInfo() {
//        https://www.jinye.cn/marketing-orderplatform/ui/pages/index.html
        OkHttpClient client = new OkHttpClient();
        String url = "https://www.jinye.cn/marketing-orderplatform/ui/pages/index.html?_u=140105122422"; // 替换为目标网址
//        Request.Builder builder = CUtil.setCookie(new Request.Builder(), Info.JinyeCookieMap);
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            Headers headers = response.headers();
            String string = response.body().string();
            System.out.println(string);
            CUtil.set_SetCookie(headers, Info.JinyeCookieMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void getYYTJSESSIONIDAndUiInfo2() {
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new RedirectInterceptor()).build();

        Request request = new Request.Builder()
                .url("https://www.jinye.cn/marketing-orderplatform/ui/pages/index.html")
                .get()
                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Connection", "keep-alive")
                .addHeader("Host", "www.jinye.cn")
                .addHeader("Pragma", "no-cache")
                .addHeader("Sec-Fetch-Dest", "document")
                .addHeader("Sec-Fetch-Mode", "navigate")
                .addHeader("Sec-Fetch-Site", "none")
                .addHeader("Sec-Fetch-User", "?1")
                .addHeader("Upgrade-Insecure-Requests", "1")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0")
                .addHeader("sec-ch-ua", "\"Microsoft Edge\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            System.out.println(response.body().string());
            System.out.println(1111);
            System.out.println(response.headers());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    static class RedirectInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);

            // 检查是否是302重定向
            if (response.code() == 302) {
                // 获取重定向的URL
                String location = response.header("Location");
                if (location != null) {
                    HttpUrl newUrl = HttpUrl.parse(location);
                    // 创建新的请求来跟随重定向
                    Request newRequest = request.newBuilder()
                            .url(newUrl)
                            .build();
                    // 手动跟随重定向
                    return chain.proceed(newRequest);
                }
            }

            return response;
        }
    }
}
